package com.hyh.eblog.shiro;

import cn.hutool.json.JSONUtil;
import com.hyh.eblog.common.lang.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 判断请求是否为ajax
 * @author Summerday
 */
public class AuthFilter extends UserFilter {

    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        // 判断是否为ajax
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String header = httpServletRequest.getHeader("X-Requested-With");
        if("XMLHttpRequest".equals(header)){
            boolean authenticated = SecurityUtils.getSubject().isAuthenticated();
            if(!authenticated){
                response.setContentType("application/json;charset=YTF-8");
                response.getWriter().print(JSONUtil.toJsonStr(Result.fail("请先登录")));
            }
        }else{
            // web
            super.redirectToLogin(request, response);
        }

    }
}
